import { _decorator, Component,RigidBody2D, instantiate, Node, Prefab ,find} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Healthy')
export class Healthy extends Component {

    @property(Prefab) dieEffect:Prefab|null=null;
   @property  curHp:number=10;

   @property invincible:boolean=false;

    protected onLoad(): void {
        
        this.node.on("DIE",this.die,this);
    }

    protected onDestroy(): void {
        this.node.off("DIE",this.die,this);
    }
    
    getInvincible(){
        return this.invincible;
    }
    setInvincible(val:boolean){
        this.invincible=val;
    }
    

    die(){
       let n:Node= instantiate(this.dieEffect);
       find("Canvas").addChild(n);
       let {x,y}=this.node.getPosition();
       n.setPosition(x,y);

       this.destorySelf();
    }
    destorySelf(){

        try {
            this.scheduleOnce(()=>{
                this.node.active=false;
                let rb2d=this.node.getComponent(RigidBody2D);
                if(rb2d){
                  rb2d.enabled=true;
                }
          
                this.node.destroy();
            },0.02);
        } catch (error) {
            
        }

       }
    reduceHp(val:number){
        if(this.invincible) return;

        this.curHp-=val;

        this.node.emit("HURT",this.curHp);

        if(this.curHp<=0){
            this.node.emit("DIE");
        }
    }



}


